package com.aramis.mydytt.ui.recommend

import androidx.lifecycle.MutableLiveData
import com.aramis.mydytt.ext.logD
import com.aramis.mydytt.ext.logE
import com.aramis.mydytt.ui.base.BaseViewModel
import com.aramis.mydytt.ui.bean.MovieItemWrapperBean
import com.aramis.mydytt.ui.bean.MovieTagBean
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class MainRecommendViewModel : BaseViewModel() {
    val movieListData = MutableLiveData<List<MovieItemWrapperBean>?>()
    private val movieList = mutableListOf<MovieItemWrapperBean>()
    private val movieTagList = mutableListOf<MovieTagBean>()
    private var movieListSize = 0

    //今日推荐
    fun getRecommendToday() {
        val subscribe = movieApi.getRecommendToday().subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                logD("今日推荐成功：$it")
            }, {
                logE("今日推荐失败：${it.message}")
            })
        compositeDisposable.add(subscribe)
    }

    //电影标签
    fun getMovieTag() {
        movieListSize = 0
        movieList.clear()
        movieTagList.clear()
        compositeDisposable.add(
            movieApi.getMovieTag().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ dataWrapper ->
                    logD("Thread:${Thread.currentThread().name} tag成功：$dataWrapper")
                    dataWrapper.data?.run {
                        movieListSize = this.size
                        this.forEach { movieTagBean ->
                            movieTagList.add(movieTagBean)
                            getMovieList(movieTagBean)
                        }
                    }
                }, {
                    movieListSize = 0
                    logE("Thread:${Thread.currentThread().name} tag失败：${it.message} ${it::class.java.name}")
                    movieListData.postValue(null)
                })
        )
    }

    //电影列表
    private fun getMovieList(movieTagBean: MovieTagBean) {
        compositeDisposable.add(
            movieApi.getMovieList(movieTagBean.id).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    movieList.add(MovieItemWrapperBean(movieTagBean.name, it.data, movieTagBean.id))
                    if (movieListSize != 0 && movieList.size == movieListSize) {
                        movieList.sortWith(compareBy { wrapper -> wrapper.tagId })
                        movieListData.postValue(movieList)
                    }
                }, {})
        )
    }

    //有数据的下拉刷新
    fun pullToRefreshMovieList() {
        if (movieTagList.isNotEmpty()) {
            movieList.clear()
            movieTagList.forEach { movieTagBean ->
                getMovieList(movieTagBean)
            }
        } else {
            getMovieTag()
        }
    }
}